<template>
    <!-- 查询部分 -->
    <pageTabelLayout>
        <template #pageHeader>
            <div style="float:right">
                <Toolbar :items="['新增', '删除', '保存',]" @add="showInsertForm" @del="deleteHandler" @saveData="updateMeters">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReady"
                style="height:calc(100% - 45px);" class='ag-theme-alpine' :defaultColDef="defaultColDef"
                :rowData="tableDataList" :columnDefs="columnDefs" :gridOptions="gridOptions" :localeText="localeTextData">
            </AgGridVuesCopys>
            <paginationCopys :total="searchData.total" show-total style="justify-content: center;margin-bottom:18px"
                @change="pageChange" :current="searchData.current" :page-size="searchData.size"></paginationCopys>

        </template>
        <a-drawer :style="{ 'zIndex': 999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd" unmountOnClose
            @ok="addMeter" @cancel="pageData.showAdd = false" cancel-text='关闭' ok-text='保存'>
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" :model="formData" layout="horizontal">
                    <a-form-item label="所属公司" field="company" label-col-flex="100px">
                        <a-input class="bacClass" placeholder="" v-model.trim="formData.company" disabled='true' />
                    </a-form-item>
                    <a-form-item label="所属部门" label-col-flex="100px" :rules="[{ required: true, message: '部门必填' }]"
                        field="department">
                        <a-cascader v-model="formData.department" :options="pageData.departmentList" allow-clear
                            ref="departmentSelect" :class="bacClass" :title="pageData.title1" @change="changes"
                            popup-container="html" />
                    </a-form-item>
                    <a-form-item label="设备编号" field="meterNo" label-col-flex="100px"
                        :rules="[{ required: true, message: '设备类型必填' }]">
                        <a-input class="bacClass" placeholder="" v-model.trim="formData.meterNo" />
                    </a-form-item>
                    <a-form-item label-col-flex="100px" field="meterName" label="设备名称"
                        :rules="[{ required: true, message: '设备名称必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input class="bacClass" v-model="formData.meterName" placeholder="" />
                    </a-form-item>
                    <a-form-item field="meterType" label="设备类型" :rules="[{ required: true, message: '设备类型必填' }]"
                        label-col-flex="100px" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html" class="bacClass" v-model="formData.meterType"
                            :filter-option="false" default-value='1'>
                            <a-option value="科隆水表">科隆水表</a-option>
                            <a-option value="南仪水表">南仪水表</a-option>
                            <a-option value="石化水表">石化水表</a-option>
                            <a-option value="利达电表">利达电表</a-option>
                            <a-option value="昊仪汽表">昊仪汽表</a-option>
                            <a-option value="科旗汽表">科旗汽表</a-option>
                            <a-option value="南仪汽表">南仪汽表</a-option>
                            <a-option value="石化汽表">石化汽表</a-option>
                            <a-option value="伊瑞汽表">伊瑞汽表</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="单位" field="unit" label-col-flex="100px">
                        <a-input v-model="formData.unit" />
                    </a-form-item>
                    <a-form-item label="区域" field="area" label-col-flex="100px">
                        <a-input v-model="formData.area" />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>


<script lang="ts">
import { onMounted, reactive, ref } from 'vue';
import Toolbar from '@/components/Toolbar.vue';
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'
import pagination from "@arco-design/web-vue/es/pagination";
import { FormInstance } from "@arco-design/web-vue/es/form";

import { localeText } from '@/api/aggridZw'
import PageTabelLayout from "@/components/pageTabelLayout.vue";
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import { slicing } from '@/utils/caseFrimAndSecRig'

const localeTextData: any = ref(localeText);
const headerShow = ref<boolean>(true)


interface FirmEntity {
    firm: string,
    firmId: string,
}

export default {

    setup() {
        const firmList = ref<FirmEntity[]>([]);

        let searchData = reactive<{
            equipmentId: string,
            companyId: number,
            total: number | string,
            current: number,
            size: number
        }>({
            equipmentId: null,
            companyId: 0,
            total: 10,
            current: 1,
            size: 10
        });



        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            departmentList: any[],
            pageLoading: boolean,
            headerShow: boolean
        }>({
            showAdd: false,
            sideTitle: "",
            departmentList: [],
            pageLoading: false,
            headerShow: true
        })

        const formData = reactive({
            meterNo: '',
            meterName: '',
            meterType: '',
            company: '',
            department: '',
            area: '',
            unit: ''
        });

        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
        }

        const columnDefs = [
            {
                showRowGroup: 'hide_def',
                "headerName": "",
                "checkboxSelection": true,
                "headerCheckboxSelection": true,
                "pinned": "left",
                "width": 200,
                resizable: false,
                filter: false,
                sortable: false,
                minWidth: 50,
                maxWidth: 50,
                lockPosition: "left",
            },
            {
                headerName: '设备编号',
                field: 'meterNo',
                width: 265
            },
            {
                headerName: '设备名称',
                field: 'meterName',
                editable: true,
                width: 265
            },
            {
                headerName: '设备类型',
                field: 'meterType',
                width: 265
            },
            {
                headerName: '所属部门',
                field: 'department',
                width: 265
            },
            {
                headerName: '计量单位',
                field: 'unit',
                editable: true,
                width: 265
            },
            {
                headerName: '最后取数时间',
                field: 'readDate',
                width: 265
            },
        ]


        let tableDataList = ref([]);
        let gridOptions = ref();
        let departmentSelect = ref();

        const gridReady = (params: any) => {
            gridOptions = params.api;

        }

        const loadMeters = () => {
            pageData.pageLoading = true;
            console.log(searchData.companyId);
            post({
                url: "ems/energyMeter/findPagedMeters",
                data: searchData
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        console.log(gridOptions);
                        searchData.total = data.total;
                        gridOptions.setRowData(data.records);
                        tableDataList.value = data.records;
                    }
                });
        }


        // 公司下拉框 改变
        const findDepartmentList = (param) => {
            post({
                url: 'org/baCompany/getDepartmentTree?companyId=' + param,
            }).then((result) => {
                if (result.code === 200) {
                    pageData.departmentList = result.data
                }
            })
        };



        const pageChange = (val: any) => {
            searchData.current = val;
            loadMeters();
        }

        onMounted(() => {
            initData();
        })

        const initData = () => {
            post({
                url: 'ems/common/fetchUserInfoByToken',
                async: false,
                data: {}
            }).then(({ code, message, data }) => {
                if (code === 200) {
                    formData.company = data.firmName;
                    console.log(data.firmId);
                    searchData.companyId = data.firmId;
                    loadMeters();
                    findDepartmentList(data.firmId);
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }
            })
        }


        const showInsertForm = () => {
            pageData.showAdd = true;
            pageData.sideTitle = "新增设备";
        };

        const formRef = ref<FormInstance>();

        const addMeter = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    console.log(formData.company);
                    post({
                        url: "ems/energyMeter/saveMeter",
                        data: formData
                    }).then((res: any) => {
                        if (res.code === 200) {
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            Message.success({
                                content: "新增成功",
                                duration: 5000,
                            });
                            //将列表重置为第一页
                            searchData.current = 1;
                            loadMeters();
                        }
                    });
                }
            });
        };


        const updateMeters = () => {
            console.log(tableDataList.value);
            post({
                url: "ems/energyMeter/batchUpdateMeters",
                data: tableDataList.value
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        loadMeters();
                    }
                });
        }


        const deleteHandler = () => {
            let rowIds = gridOptions.getSelectedRows().map((item) => item.id)
            if (rowIds.length === 0) {
                Message.warning("请选择要删除的数据！");
                return;
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {
                    post({
                        url: "ems/energyMeter/deleteMeters",
                        data: rowIds,
                    }).then(({ code, data, message }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            loadMeters();
                        }

                    });
                },
            });
        }

        const changes = () => {
            nextTick(() => {
                formData.department = slicing(departmentSelect.value.selectViewValue[0].label)
            })
        }
        return {
            localeTextData,
            changes,
            pageChange,
            headerShow,
            departmentSelect,
            formData,
            columnDefs,
            initData,
            findDepartmentList,
            loadMeters,
            updateMeters,
            tableDataList,
            defaultColDef,
            gridOptions,
            gridReady,
            deleteHandler,
            showInsertForm,
            addMeter,
            formRef,
            firmList,
            pageData,
            searchData,

        };
    },

    components: { PageTabelLayout, CorporateSectorCascader }

};
</script>

<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>
